package cn.mrlong.imagetocolorvalue;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import io.reactivex.functions.Consumer;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MainActivity extends AppCompatActivity {

    private Button selectImg;
    private ImageView showImg;
    private RecyclerView recyclerView;

    private List<Map.Entry<Integer, Integer>> list;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();

    }

    private void initListener() {
        selectImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkPermission();
            }
        });
    }

    private void initView() {
        selectImg = findViewById(R.id.selectImg);
        showImg = findViewById(R.id.showImg);
        recyclerView = findViewById(R.id.recyclerView);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter(this, new ArrayList<Integer>());
        recyclerView.setAdapter(adapter);
    }

    class MyAdapter extends RecyclerView.Adapter<MyHolder> {
        private Context context;
        private List<Integer> datas;

        public MyAdapter(Context context, List<Integer> datas) {
            this.datas = datas;
            this.context = context;
        }

        @Override
        public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
            MyHolder holder = new MyHolder(v);
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull MainActivity.MyHolder holder, int position) {
            holder.setData(datas.get(position));
        }

        @Override
        public int getItemCount() {
            return datas.size();
        }

        public void add(int key) {
            this.datas.add(key);
            notifyDataSetChanged();
        }
    }

    class MyHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public MyHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.item);
        }

        public void setData(int colorVal) {
            textView.setBackgroundColor(colorVal);
            textView.setText(String.format("#%06X", colorVal));
        }
    }

    public void checkPermission() {
        new RxPermissions(this)
                .request(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //打开照相机
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(intent, 1);
                        } else {
                            showMessage("需要相机、读写内存卡权限请授权！");
                        }
                    }
                });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    showImg.setImageBitmap(bm);
                    getColors(bm);
                }
                break;
        }
    }

    ConcurrentHashMap<Integer, Integer> allColor = new ConcurrentHashMap<Integer, Integer>();

    private void getColors(final Bitmap bm) {
        new Thread() {
            @Override
            public void run() {
                super.run();

                for (int y = 0; y < bm.getHeight(); y++) {
                    for (int x = 0; x < bm.getWidth(); x++) {
                        //获得像素的颜色
                        int color = bm.getPixel(x, y);
                        if (allColor.containsKey(color)) {
                            int val = allColor.get(color);
                            allColor.put(color, val + 1);
                        } else {
                            allColor.put(color, 1);
                        }
                    }
                }
                float[] hsv1 = new float[3];
                float[] hsv2 = new float[3];

                Log.e("===>前", "" + allColor.keySet().size());


                for (int i = 0; i < 10; i++) {
                    if (allColor.entrySet().size() > i) {
                        Iterator<Map.Entry<Integer, Integer>> iterator = allColor.entrySet().iterator();
                        Map.Entry<Integer, Integer> first = iterator.next();

                        for (int i1 = 0; i1 < i; i1++) {
                            first = iterator.next();
                        }
                        while (iterator.hasNext()) {
                            Map.Entry<Integer, Integer> second = iterator.next();
                            Color.colorToHSV(first.getKey(), hsv1);
                            Color.colorToHSV(second.getKey(), hsv2);
                            if (checkColorSimilar(hsv1, hsv2)) {
                                first.setValue(first.getValue() + second.getValue());
                                Log.e("==>", "移除");
                                iterator.remove();
                            }
                        }
                    }
                }

                Log.e("===>后", "" + allColor.keySet().size());
                list = new ArrayList<>(allColor.entrySet());
                Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
                    @Override
                    public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                        return (o2.getValue() - o1.getValue());
                    }
                });

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //用迭代器对list中的键值对元素进行遍历
                        Iterator<Map.Entry<Integer, Integer>> iter = list.iterator();
                        if (list.size() >= 10) {
                            for (int i = 0; i < 10; i++) {
                                Map.Entry<Integer, Integer> item = iter.next();
                                int key = item.getKey();
                                int value = item.getValue();
                                Log.e("==>", String.format("#%06X", key) + "   " + value);
                                adapter.add(key);
                            }
                        } else {
                            while (iter.hasNext()) {
                                Map.Entry<Integer, Integer> item = iter.next();
                                int key = item.getKey();
                                int value = item.getValue();
                                Log.e("==>", String.format("#%06X", key) + "   " + value);
                                adapter.add(key);
                            }
                        }
                    }
                });

            }
        }.start();
    }


    private boolean checkColorSimilar(float[] hsv1, float[] hsv2) {
        double similarH = 10f;
        double similarS = 0.05;
        double similarV = 0.05;
        if (hsv1[0] > 360 - similarH && hsv2[0] < similarH) {
            hsv1[0] = 360f - hsv1[0];
        }
        if (Math.abs(hsv1[0] - hsv2[0]) < similarH) {
            return true;
        } else if (Math.abs(hsv1[0] - hsv2[0]) < similarH * 2 && Math.abs(hsv1[1] - hsv2[1]) < similarS) {
            return true;
        } else if (Math.abs(hsv1[0] - hsv2[0]) < similarH * 2 && Math.abs(hsv1[2] - hsv2[2]) < similarV) {
            return true;
        } else {
            return false;
        }
    }

    public void showMessage(String message) {
        Toast.makeText(this, "" + message, Toast.LENGTH_SHORT).show();
    }
}